import type { PriceModel, ResourcePricing } from './types';

import { mockRequestClient as defHttp } from '#/api/request';

enum Api {
  // 定价模型管理
  PricingModel = '/resource/pricing/model',

  // 客户侧定价
  CustomerPricing = '/resource/pricing/customer',

  // 平台侧定价
  PlatformPricing = '/resource/pricing/platform',

  // 订阅管理
  Subscription = '/resource/pricing/subscription',

  // 交易管理
  Transaction = '/resource/pricing/transaction',

  // 分润管理
  RevenueShare = '/resource/pricing/revenue-share',

  // 价格计算
  Calculate = '/resource/pricing/calculate',

  // 价格历史
  History = '/resource/pricing/history',

  // 价格策略
  Strategy = '/resource/pricing/strategy',

  // 价格审批
  Approval = '/resource/pricing/approval',
}

// 定价模型参数
export interface PricingModelParam {
  resourceId: string;
  modelId: string;
  name: string;
  type: 'fixed' | 'usage' | 'tiered' | 'subscription' | 'auction';
  description: string;

  // 客户侧定价
  customerPricing: {
    currency: string;
    basePrice: number;
    unitPrice?: number;
    tiers?: Array<{
      min: number;
      max?: number;
      price: number;
    }>;
    discounts?: Array<{
      type: 'percentage' | 'fixed';
      value: number;
      conditions?: any;
    }>;
  };

  // 平台侧定价
  platformPricing: {
    cost: number;
    margin: number;
    commission?: number;
    revenueShare?: number;
  };

  enabled: boolean;
}

// 订阅参数
export interface SubscriptionParam {
  resourceId: string;
  customerId: string;
  planId: string;
  startDate: string;
  endDate?: string;
  quantity: number;
  autoRenew: boolean;
  paymentMethod: string;
}

// 交易参数
export interface TransactionParam {
  resourceId: string;
  customerId: string;
  quantity: number;
  unitPrice: number;
  currency: string;
  paymentMethod: string;
  metadata?: any;
}

// 分润参数
export interface RevenueShareParam {
  resourceId: string;
  transactionId: string;
  parties: Array<{
    partyId: string;
    partyType: 'platform' | 'provider' | 'partner';
    sharePercentage: number;
    amount: number;
  }>;
}

// 价格计算参数
export interface PriceCalculationParam {
  resourceId: string;
  customerId: string;
  quantity: number;
  usage?: any;
  discounts?: string[];
  currency: string;
}

// 价格计算结果
export interface PriceCalculationResult {
  originalPrice: number;
  discountedPrice: number;
  finalPrice: number;
  currency: string;
  breakdown: {
    basePrice: number;
    unitPrice: number;
    tierDiscount: number;
    customDiscounts: number;
    taxes: number;
  };
  appliedDiscounts: Array<{
    type: string;
    description: string;
    amount: number;
  }>;
}

// 价格策略
export interface PricingStrategy {
  id: string;
  name: string;
  description: string;
  type: 'dynamic' | 'seasonal' | 'competitive' | 'custom';
  rules: Array<{
    condition: any;
    action: 'adjust' | 'discount' | 'premium';
    value: number;
  }>;
  enabled: boolean;
  priority: number;
}

/**
 * 双视角定价模型API
 */
export const ResourcePricingApi = {
  /**
   * 创建定价模型
   */
  createPricingModel: (params: PricingModelParam) =>
    defHttp.post<PriceModel>({
      url: Api.PricingModel,
      data: params,
    }),

  /**
   * 更新定价模型
   */
  updatePricingModel: (modelId: string, params: Partial<PricingModelParam>) =>
    defHttp.put<PriceModel>({
      url: `${Api.PricingModel}/${modelId}`,
      data: params,
    }),

  /**
   * 获取定价模型
   */
  getPricingModel: (modelId: string) =>
    defHttp.get<PriceModel>({
      url: `${Api.PricingModel}/${modelId}`,
    }),

  /**
   * 删除定价模型
   */
  deletePricingModel: (modelId: string) =>
    defHttp.delete<void>({
      url: `${Api.PricingModel}/${modelId}`,
    }),

  /**
   * 获取资源的所有定价模型
   */
  getResourcePricingModels: (resourceId: string) =>
    defHttp.get<PriceModel[]>({
      url: `${Api.PricingModel}/resource/${resourceId}`,
    }),

  /**
   * 计算价格
   */
  calculatePrice: (params: PriceCalculationParam) =>
    defHttp.post<PriceCalculationResult>({
      url: Api.Calculate,
      data: params,
    }),

  /**
   * 创建订阅
   */
  createSubscription: (params: SubscriptionParam) =>
    defHttp.post<{
      subscriptionId: string;
      status: 'active' | 'pending' | 'cancelled';
      nextBillingDate: string;
    }>({
      url: Api.Subscription,
      data: params,
    }),

  /**
   * 更新订阅
   */
  updateSubscription: (
    subscriptionId: string,
    params: Partial<SubscriptionParam>,
  ) =>
    defHttp.put<{
      success: boolean;
      message: string;
    }>({
      url: `${Api.Subscription}/${subscriptionId}`,
      data: params,
    }),

  /**
   * 取消订阅
   */
  cancelSubscription: (subscriptionId: string, reason?: string) =>
    defHttp.delete<{
      success: boolean;
      message: string;
    }>({
      url: `${Api.Subscription}/${subscriptionId}`,
      params: { reason },
    }),

  /**
   * 创建交易
   */
  createTransaction: (params: TransactionParam) =>
    defHttp.post<{
      transactionId: string;
      status: 'pending' | 'completed' | 'failed';
      amount: number;
      currency: string;
    }>({
      url: Api.Transaction,
      data: params,
    }),

  /**
   * 获取交易详情
   */
  getTransaction: (transactionId: string) =>
    defHttp.get<{
      transactionId: string;
      resourceId: string;
      customerId: string;
      amount: number;
      currency: string;
      status: string;
      createdAt: string;
      metadata?: any;
    }>({
      url: `${Api.Transaction}/${transactionId}`,
    }),

  /**
   * 创建分润记录
   */
  createRevenueShare: (params: RevenueShareParam) =>
    defHttp.post<{
      revenueShareId: string;
      status: 'pending' | 'processed' | 'failed';
    }>({
      url: Api.RevenueShare,
      data: params,
    }),

  /**
   * 获取分润记录
   */
  getRevenueShares: (resourceId: string, timeRange?: string) =>
    defHttp.get<
      Array<{
        revenueShareId: string;
        transactionId: string;
        parties: Array<{
          partyId: string;
          partyType: string;
          sharePercentage: number;
          amount: number;
          status: string;
        }>;
        totalAmount: number;
        createdAt: string;
      }>
    >({
      url: `${Api.RevenueShare}/${resourceId}`,
      params: { timeRange },
    }),

  /**
   * 获取价格历史
   */
  getPriceHistory: (resourceId: string, timeRange: string) =>
    defHttp.get<
      Array<{
        timestamp: string;
        price: number;
        currency: string;
        changeType: 'increase' | 'decrease' | 'new';
        reason?: string;
      }>
    >({
      url: `${Api.History}/${resourceId}`,
      params: { timeRange },
    }),

  /**
   * 创建价格策略
   */
  createPricingStrategy: (params: PricingStrategy) =>
    defHttp.post<PricingStrategy>({
      url: Api.Strategy,
      data: params,
    }),

  /**
   * 获取价格策略列表
   */
  getPricingStrategies: (resourceId?: string) =>
    defHttp.get<PricingStrategy[]>({
      url: Api.Strategy,
      params: { resourceId },
    }),

  /**
   * 提交价格审批
   */
  submitPriceApproval: (modelId: string, reason: string) =>
    defHttp.post<{
      approvalId: string;
      status: 'pending' | 'approved' | 'rejected';
    }>({
      url: Api.Approval,
      data: { modelId, reason },
    }),

  /**
   * 审批价格变更
   */
  approvePriceChange: (
    approvalId: string,
    approved: boolean,
    comment?: string,
  ) =>
    defHttp.put<{
      success: boolean;
      message: string;
    }>({
      url: `${Api.Approval}/${approvalId}`,
      data: { approved, comment },
    }),
};
